package com.eden.manage.config;

import com.eden.manage.dto.UserInfoDto;
import com.eden.manage.service.LoginService;
import com.eden.manage.utils.LoginUtils;
import eden.api.common.utils.ErrorEnums;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

@Component
@Slf4j
public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
            return true;
        }
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            log.info(headerName + ": " + request.getHeader(headerName));
        }
        String token = request.getHeader("Authorization");

        if (token == null || !token.startsWith("Bearer ")) {
            throw new RuntimeException(ErrorEnums.NO_AUTH.name());
        }
        String dbToken = token.replace("Bearer ","");
        UserInfoDto userInfo = loginService.getUserInfo(dbToken);
        String source = String.format(LoginUtils.loginTokenKey, userInfo.getUserAccount(), userInfo.getUserPassword());
        boolean validateLogin = LoginUtils.validateToken(dbToken, source, 7);
        if(!validateLogin){
            throw new RuntimeException(ErrorEnums.NO_AUTH.name());
        }
        return super.preHandle(request,response,handler);
    }
}
